package com.team5.reptiles;

import com.team5.entity.CashFlow;
import com.team5.mapper.CashFlowMapper;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class CashFlowRep {
    @Autowired
    CashFlowMapper cashFlowMapper;
    private static final Logger logger = Logger.getLogger(CashFlow.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "0 0/10 * * * ?") // 每10分钟执行一次
    public void fetchCashFlowData() {
        cashFlowMapper.deleteAll();
        int logId = LogIdGenerator.getNextLogId(); // 获取日志ID

        long startTime = System.currentTimeMillis(); // 记录爬虫开始时间

        // 设置 ChromeDriver 路径
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\86155\\Desktop\\chrome-win64\\chromedriver.exe");

        // 配置 ChromeOptions
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--headless"); // 启用无头模式
        options.addArguments("--disable-gpu"); // 适用于 Windows 操作系统
        options.addArguments("--no-sandbox");

        // 初始化 WebDriver
        WebDriver driver = new ChromeDriver(options);

        try {
            // 定义要抓取的 URL
            String url = "https://data.eastmoney.com/hsgt/hsgtV2.html";
            driver.get(url);

            // 等待页面完全加载
            driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

            // 获取页面源代码
            String pageSource = driver.getPageSource();

            // 使用 Jsoup 解析 HTML
            Document doc = Jsoup.parse(pageSource);

            // 选择所有匹配的元素
            Elements dataTbody = doc.select("tbody.north_table,tbody.hk_table");
            // 输出标题到控制台
            for (int k = 0; k < dataTbody.size(); k++) {
                // 选择行内元素
                Element tbody = dataTbody.get(k);
                Elements dataElements;
                if (k == 0) {
                    dataElements = tbody.select("tr.bbLightBlue");
                } else {
                    dataElements = tbody.select("tr");
                }

                // 遍历每一行
                for (int i = 0; i < dataElements.size(); i++) {
                    Element element = dataElements.get(i);
                    Elements row = element.select("td");
                    CashFlow cashFlow= new CashFlow();
                    // 确保每行至少有足够的列
                    if (row.size() > 5) {
                        if (i % 2 == 0) {
                            // 从每一列获取数据
                            String sector = row.get(1).text();
                            String netBuy = row.get(3).text();
                            String limitText1 = row.get(4).text();
                            String limitText2 = row.get(5).text();

                            // 处理金额单位，去除单位并转换为 BigDecimal
                            BigDecimal limit1 = parseAmountString(limitText1);
                            BigDecimal limit2 = parseAmountString(limitText2);
                            BigDecimal money=parseAmountString(netBuy);
                            // 将字符串转换为 BigDecimal 进行精确计算
                            BigDecimal total = limit1.add(limit2);
                            cashFlow.setName(sector);
                            cashFlow.setFlow(money.doubleValue());
                            cashFlow.setMoney(limit2.doubleValue());
                            cashFlow.setMaxnum(total.doubleValue());
                            System.out.println(cashFlow);
                            cashFlowMapper.insert(cashFlow);
                        } else {
                            String sector = row.get(0).text();
                            String netBuy = row.get(2).text();
                            String limitText1 = row.get(3).text();
                            String limitText2 = row.get(4).text();

                            // 处理金额单位，去除单位并转换为 BigDecimal
                            BigDecimal limit1 = parseAmountString(limitText1);
                            BigDecimal limit2 = parseAmountString(limitText2);
                            BigDecimal money=parseAmountString(netBuy);
                            // 将字符串转换为 BigDecimal 进行精确计算
                            BigDecimal total = limit1.add(limit2);
                            cashFlow.setName(sector);
                            cashFlow.setFlow(money.doubleValue());
                            cashFlow.setMoney(limit2.doubleValue());
                            cashFlow.setMaxnum(total.doubleValue());
                            System.out.println(cashFlow);
                            cashFlowMapper.insert(cashFlow);
                        }
                    }
                }
            }

        } catch (Exception e) {
            logger.error("Error fetching cash flow data: " + e.getMessage());
        } finally {
            // 关闭 WebDriver
            if (driver != null) {
                driver.quit();
            }
        }

        long endTime = System.currentTimeMillis(); // 记录爬虫结束时间

        // 记录爬虫结束信息
        String logMessageEnd = "日志ID: " + logId +
                "，爬虫行为说明: 抓取沪深港通资金流数据" +
                ", 爬虫网址: https://data.eastmoney.com/hsgt/hsgtV2.html"+
                "，爬虫开始时间: " + dateFormat.format(new Date(startTime)) +
                "，爬虫结束时间: " + dateFormat.format(new Date(endTime)) +
                "，爬虫数据表: 沪深港通资金流";
        logger.info(logMessageEnd);
    }

    // 解析带有单位的金额字符串
    private BigDecimal parseAmountString(String amountText) {
        if (amountText.contains("亿元")) {
            return new BigDecimal(amountText.replace("亿元", ""));
        } else if (amountText.contains("万元")) {
            return new BigDecimal(amountText.replace("万元", "")).divide(BigDecimal.valueOf(10000), 2, BigDecimal.ROUND_HALF_UP);
        } else {
            return BigDecimal.ZERO;
        }
    }
}

